<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/9/28
 * Time: 16:17
 */
class services{
    //筛选条件服务类别
    private function servicesType(){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $servicesType = M("services_type");
        Session::switchCustomer($customerId);
        $where['cId']=array("eq",$customerId);
        $arr = $servicesType->where($where)->field("id,name")->select();
        return $arr;
    }
    //筛选条件服务对象
    private function servicesDivision(){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $servicesDivision = M("services_division");
        Session::switchCustomer($customerId);
        $where['cId']=array("eq",$customerId);
        $arr = $servicesDivision->where($where)->field("id,name")->select();
        return $arr;
    }
    //筛选条件
    public function servicesCondition(){
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $servicesUser = M("services_division_user");
        $servicesManager = M("services_manager");
        $servicesMessage  = M("services_message");
        Session::switchCustomer($customerId);
        //判断身份
        $userInfo = $servicesManager->where("openid='$userName'")->find();
        if(!$userInfo){
            $userInfo = $servicesUser->alias("a")
                ->join("inner join wx_services_division b on a.divisionId=b.id")
                ->where("a.openid='$userName' and b.cId=$customerId")
                ->field("b.id")
                ->find();
            if(!$userInfo){
                Output::instance()->resultCode(1,"无访问权限");
                return;
            }else{
               $identity=0;
               $tplHtml = "day";
            }
        }else{
            $identity=1;
            $tplHtml = "day_admin";
            $result['division']=self::servicesDivision();
        }
        $result['type']=self::servicesType();
        $result['identity']=$identity;
        Output::instance()->module("services",$tplHtml)->object($result);
    }
    //列表
    public function servicesMessageList($typeId=null,$divisionId=null,$start=0,$limit=10){
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $servicesUser = M("services_division_user");
        $servicesManager = M("services_manager");
        $servicesMessage  = M("services_message");
        Session::switchCustomer($customerId);
        //判断身份
        $userInfo = $servicesManager->where("openid='$userName'")->find();
        if(!$userInfo){
            $userInfo = $servicesUser->alias("a")
                ->join("inner join wx_services_division b on a.divisionId=b.id")
                ->where("a.openid='$userName' and b.cId=$customerId")
                ->field("b.id")
                ->find();
            if(!$userInfo){
                Output::instance()->resultCode(1,"无访问权限");
                return;
            }else{
                $where['_string']="a.divisionId=".$userInfo['id']." or a.allPerson=1";
            }
        }else{
            if(!$userInfo['identity']){
				$where['a.managerId']=array("eq",$userInfo['id']);
            }else{
                $identity=1;
            }
			if($divisionId){
				if($divisionId=='all'){
					$where['a.allPerson']=array("eq",1);
				}else{
					$where['divisionId']=array("eq",$divisionId);
				}
			}
        }
        $typeId?$where['a.typeId']=array('eq',$typeId):"";
        $where['a.deleted']=array("eq",0);
        $where['a.cId']=array("eq",$customerId);
        $result['list'] = $servicesMessage->alias("a")
            ->join("inner join wx_services_type c on a.typeId=c.id")
            ->join("inner join wx_services_manager d on d.id=a.managerId")
            ->join("wx_services_division e on a.divisionId=e.id")
            ->join("inner join wx_".$customerId."_user_weixin_info b on d.userId=b.id")
            ->where($where)
            ->field("a.id,a.allPerson,a.content,a.image,b.nickname,b.headimgurl,b.openid,a.createTime,c.name as typeName,e.name as divisionName")
            ->order("a.createTime desc")
            ->limit($start,$limit)
            ->select();
        foreach($result['list'] as $key=>$value){
            if($value['image']){
                $result['list'][$key]['image']=explode(",",$value['image']);
            }
            if($value['openid']==$userName||$identity){
                $result['list'][$key]['canDel']=1;
            }else{
                $result['list'][$key]['canDel']=0;
            }
            $update = date("Y-m-d",strtotime($value["createTime"]));
            $datatime=date('Y-m-d');
            $yesterday = date("Y-m-d",time()-24*60*60);
            if($update==$datatime){
                $result['list'][$key]["createTime"] = "今天 ".date("H:i",strtotime($value["createTime"]));
            }else if($update==$yesterday){
                $result['list'][$key]["createTime"] = "昨天 ".date("H:i",strtotime($value["createTime"]));
            }else{
                $result['list'][$key]["createTime"] = date("Y年m月d日 H:i",strtotime($value["createTime"]));
            }
            if($value['allPerson']){
                $result['list'][$key]['divisionName']="所有人";
            }
        }
        $result['total'] =  $servicesMessage->alias("a")
            ->join("inner join wx_services_type c on a.typeId=c.id")
            ->join("inner join wx_services_manager d on d.id=a.managerId")
            ->join("inner join wx_".$customerId."_user_weixin_info b on d.userId=b.id")
            ->where($where)->count();
        Output::instance()->object($result);
    }
    //服务统计
    public function servicesStatistics(){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $servicesType = M("services_type");
        $servicesMessage  = M("services_message");
        Session::switchCustomer($customerId);
        $result['list'] = $servicesType->alias("a")
            ->join("wx_services_message b on a.id=b.typeId and b.deleted=0")
            ->field("a.name,count(b.id) as count")
            ->where("a.cId=$customerId")
            ->group("a.id")
            ->select();
        $result['total'] = $servicesMessage->where("cId=$customerId and deleted=0")->count();
        Output::instance()->module("services","total")->object($result);
    }
    //详情
    public function servicesDetail($id){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $servicesMessage  = M("services_message");
        Session::switchCustomer($customerId);
        $detail = $servicesMessage->alias("a")
            ->join("inner join wx_services_manager d on d.id=a.managerId")
			->join("wx_services_division e on a.divisionId=e.id")
            ->join("inner join wx_".$customerId."_user_weixin_info b on d.userId=b.id")
            ->join("inner join wx_services_type c on a.typeId=c.id")
            ->where("a.id=$id")
            ->field("a.content,a.allPerson,a.image,b.nickname,b.headimgurl,c.name,a.createTime,e.name as divisionName")
            ->find();
        if($detail['image']){
            $detail['image']=explode(",",$detail['image']);
        }
        if($detail){
			if($detail['allPerson']){
                $detail['divisionName']="所有人";
            }
            $update = date("Y-m-d",strtotime($detail["createTime"]));
            $datatime=date('Y-m-d');
            $yesterday = date("Y-m-d",time()-24*60*60);
            if($update==$datatime){
                $detail["createTime"] = "今天 ".date("H:i",strtotime($detail["createTime"]));
            }else if($update==$yesterday){
                $detail["createTime"] = "昨天 ".date("H:i",strtotime($detail["createTime"]));
            }else{
                $detail["createTime"] = date("Y年m月d日 H:i",strtotime($detail["createTime"]));
            }
        }
        Output::instance()->module("services","day_detail")->object($detail);
    }
    //添加服务页面
    public function servicesIndex(){
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $servicesManager = M("services_manager");
        Session::switchCustomer($customerId);
        $result['managerId']=$servicesManager->where("openid='$userName'")->getField("id");
        if(!$result['managerId']){
            Output::instance()->resultCode(1,"无访问权限");
            return;
        }
        $result['type']=self::servicesType();
        $result['division']=self::servicesDivision();
        Output::instance()->module("services","new")->object($result);
    }
    //保存服务
    public function saveServices($managerId,$typeId,$divisionId,$content,$image,$allPerson=0){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $servicesMessage  = M("services_message");
        $servicesDivisionUser = M("services_division_user");
        $servicesType = M("services_type");
        Session::switchCustomer($customerId);
        $templateModel = M('template_messages');
        $data['cId']=$customerId;
        $data['divisionId']=$divisionId;
        $data['managerId']=$managerId;
        $data['typeId']=$typeId;
        $data['content']=$content;
        $data['image']=$image;
        $data['allPerson']=$allPerson;
        $data['createtime']=date("Y-m-d H:i:s");
        $massageId = $servicesMessage->add($data);
        if(!$allPerson){
            $typeName = $servicesType->where("id=$typeId")->getField("name");
            $templatemsg = $templateModel->where(['status' => 'seriversComplete'])->find();
            $template_id = $templatemsg['templateId'];
            $data['first'] = array('value' => '一条新的服务日志已经为您生成', 'color' => "#743A3A");
            $data['keyword1'] = array('value' => $typeName, 'color' => '#173177');
            $data['keyword2'] = array('value' => $data['createtime'], 'color' => '#173177');
            $data['remark'] = array('value' => '点击查看详情', "color" => '#008000');
            $url = C("SERVER_HOST") . "call.html?customerId=" . $customerId . "&module=services&method=servicesDetail&params={\"id\":" . $massageId . "}";//链接;//链接
            $topcolor = "#FF0000";
            $arr = $servicesDivisionUser->where("divisionId=$divisionId")->field("openid")->select();
            foreach($arr as $key=>$value){
                $toUser = $value['openid'];//发送给谁（微信的openid）
                WeixinApi::sendTpl($toUser, $template_id, $url, $topcolor, $data);
            }

        }
        if($massageId){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //删除日志
    public function delServicesMassage($id){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $servicesMessage  = M("services_message");
        Session::switchCustomer($customerId);
        $result = $servicesMessage->where("id=$id")->setField("deleted",1);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }

}